package com.wfyvv.fast.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 *
 * @author fengyu.wang
 * @since 2017-12-27 09:54:00
 */
@Component
@AllArgsConstructor
public class RedisService {
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 默认过期时长，单位：秒
     */
    private final static long DEFAULT_EXPIRE = 60 * 60 * 24;

    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value instanceof String ? (String) value : JSON.toJSONString(value));
    }

    public void setEx(String key, Object value) {
        redisTemplate.opsForValue().set(key, value instanceof String ? (String) value : JSON.toJSONString(value), DEFAULT_EXPIRE, TimeUnit.SECONDS);
    }

    public void setEx(String key, Object value, int expire) {
        redisTemplate.opsForValue().set(key, value instanceof String ? (String) value : JSON.toJSONString(value), expire, TimeUnit.SECONDS);
    }

    public String get(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    public <T> T get(String key, Class<T> clazz) {
        Object value = redisTemplate.opsForValue().get(key);
        return clazz.equals(String.class) ? (T) value : JSON.parseObject((String) value, clazz);
    }

    public <T> T get(String key, TypeReference<T> typeReference) {
        Object value = redisTemplate.opsForValue().get(key);
        return JSON.parseObject((String) value, typeReference);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }
}
